from flask import Blueprint, request, jsonify
from app import db
from app.models.user import User
from app.models.event import Event
from app.Tools.climb_pid import get_first_parts_from_A_arrays_v2_optimized
import time
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

auth_bp = Blueprint('auth', __name__, url_prefix='')

# 用户注册
@auth_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    
    # 只验证username和password字段
    if not all(k in data for k in ('username', 'password')):
        return jsonify({'error': '缺少用户名或密码'}), 400
    
    # 检查用户名是否已存在
    if User.query.filter_by(username=data['username']).first():
        return jsonify({'error': '用户名已存在'}), 409
    
    # 创建新用户
    new_user = User(
        username=data['username']
    )
    new_user.set_password(data['password'])  # 加密密码
    
    db.session.add(new_user)
    db.session.commit()
    
    return jsonify({
        'message': '注册成功',
        'user': new_user.to_dict()
    }), 201

# 用户登录
@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    
    if not all(k in data for k in ('username', 'password')):
        return jsonify({'error': '请提供用户名和密码'}), 400
    
    user = User.query.filter_by(username=data['username']).first()
    
    if not user or not user.check_password(data['password']):
        return jsonify({'error': '用户名或密码错误'}), 401
    
    # add_event()

    return jsonify({
        'message': '登录成功',
        'user': user.to_dict()
    }), 200